<template>
  <div class="app-container">
    <el-col>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="编号" prop="signCode">
          <el-input v-model="queryParams.signCode" placeholder="请输入编号" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="道路名称" prop="roadName">
          <el-input v-model="queryParams.roadName" placeholder="请输入道路名称" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="queryParams.location" placeholder="请输入位置(交叉口位置)" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-has-role="['record']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                     v-has-role="['record']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-has-role="['record']">删除</el-button>
        </el-col>
<!--        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                     v-hasPermi="['system:user:import']">导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['system:user:export']">导出
          </el-button>
        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" @row-dblclick="viewDetail">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="编号" align="center" key="signCode" prop="signCode" v-if="columns.signCode.visible"/>
        <el-table-column label="所属街道" align="center" key="streetName" prop="streetName" v-if="columns.streetName.visible"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="道路名称" align="center" key="roadName" prop="roadName" v-if="columns.roadName.visible"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="走向" align="center" key="direction" prop="direction" v-if="columns.direction.visible"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="位置(交叉口位置)" align="center" key="location" prop="location"
                         v-if="columns.location.visible" width="120"/>
        <el-table-column label="备注" align="center" key="remark" prop="remark"
                         v-if="columns.remark.visible" width="120"/>
        <el-table-column label="创建日期" align="center" key="createTime" prop="createTime"
                         v-if="columns.createTime.visible" />
        <el-table-column label="状态" align="center" key="status" v-if="columns.status.visible">
          <template slot-scope="scope">
            {{scope.row.status === 1?'正常': (scope.row.status === 2?'维修中' : scope.row.status === 3?'报废':'')}}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope" v-if="scope.row.userId !== 1">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-has-role="['record']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-has-role="['record']">删除
            </el-button>
            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="viewRecords" icon="el-icon-key">查看维修记录</el-dropdown-item>
                <el-dropdown-item command="addRecords" icon="el-icon-circle-check" v-has-role="['record']">增加维修记录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-col>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="地名指示牌编号" prop="signCode">
              <el-input v-model="form.signCode" placeholder="请输入地名指示牌编号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属街道" prop="streetName">
              <el-input v-model="form.streetName" placeholder="请输入所属街道" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="道路名称" prop="roadName">
              <el-input v-model="form.roadName" placeholder="请输入道路名称" maxlength="11"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="走向" prop="direction">
              <el-input v-model="form.direction" placeholder="请输入走向" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item  label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入位置(交叉口位置)" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增地名指示牌维修记录-->
    <el-dialog  @open="onOpen" @close="onClose" title="新增地名指示牌维修记录" :visible.sync="fixDialog">
      <el-form ref="elForm" :model="formData" :rules="fixrules" size="medium" label-width="100px">

          <el-form-item label="编号" prop="signCode">
            <el-input v-model="formData.signCode" placeholder="编号" maxlength="30" disabled/>
          </el-form-item>

          <el-form-item label="维修时间" prop="maintenanceDate">
            <el-date-picker v-model="formData.maintenanceDate" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                            :style="{width: '100%'}" placeholder="请选择维修时间" clearable></el-date-picker>
          </el-form-item>
          <el-form-item label="维修类别" prop="maintenanceType">
            <el-input v-model="formData.maintenanceType" placeholder="请输入维修类别" clearable
                      :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="补充说明" prop="maintenanceContent">
            <el-input v-model="formData.maintenanceContent" placeholder="请输入补充说明" clearable
                      :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="维修前照片" prop="beforePhoto" >
            <UploadImageBfr @input="methodBefore" :picUrl="(formData.beforePhoto===''||formData.beforePhoto===undefined)?null:formData.beforePhoto"></UploadImageBfr>
          </el-form-item>
          <el-form-item label="维修后照片" prop="afterPhoto" >
            <UploadImageAft @input="methodRe" :picUrl="(formData.afterPhoto===''||formData.afterPhoto===undefined)?null:formData.afterPhoto"></UploadImageAft>
          </el-form-item>
          <el-form-item label="服务费" prop="serviceFee">
            <el-input v-model="formData.serviceFee" placeholder="请输入服务费" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="配件费" prop="partsFee">
            <el-input v-model="formData.partsFee" placeholder="请输入配件费" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="维修人员" prop="maintenancePerson">
            <el-input v-model="formData.maintenancePerson" placeholder="请输入维修人员" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="维修金额(服务费+配件费)" prop="totalFee" label-width="215px">
            <el-input v-model="formData.totalFee" placeholder="请输入维修金额" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user"
import {getToken} from "@/utils/auth"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import "splitpanes/dist/splitpanes.css"
import {addRoadSign, delRoadSign, getRoad, listRoadSign, roadSignUpdate} from "@/api/road/sign";
import {addMaintenance} from "@/api/road/maintenance";
import UploadImageAft from '@/views/road/maintenance/components/fixedIndexAft'
import UploadImageBfr from '@/views/road/maintenance/components/fixedIndexBfr'

export default {
  name: "User",
  components: {UploadImageAft, UploadImageBfr},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        signCode: undefined,
        roadName: undefined,
        location: undefined
      },
      // 列信息
      columns: {
        signCode: {label: '地名指示牌编号', visible: true},
        streetName: {label: '所属街道', visible: true},
        roadName: {label: '道路名称', visible: true},
        direction: {label: '走向', visible: true},
        location: {label: '位置', visible: true},
        remark: {label: '备注', visible: true},
        createTime: {label: '创建日期', visible: true},
        status: {label: '状态', visible: true}

      },
      // 表单校验
      rules: {
        signCode: [
          {required: true, message: "编号不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '编号长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        streetName: [
          {required: true, message: "所属街道不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '所属街道长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        roadName: [
          {required: true, message: "道路名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '道路名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        direction: [
          {required: true, message: "走向不能为空", trigger: "blur"},
          {min: 1, max: 20, message: '走向长度必须介于 1 和 20 之间', trigger: 'blur'}
        ],
        location: [
          {required: true, message: "位置不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '位置长度必须介于 2 和 20 之间', trigger: 'blur'}
        ]

      },


      fixDialog: false,
      formData: {
        signCode: null,
        maintenanceDate: null,
        maintenanceType: undefined,
        maintenanceContent: undefined,
        beforePhoto: null,
        afterPhoto: null,
        serviceFee: undefined,
        partsFee: undefined,
        maintenancePerson: undefined,
        totalFee: undefined,
      },
      fixrules: {
        maintenanceDate: [{
          required: true,
          message: '请选择维修时间',
          trigger: 'change'
        }],
        maintenanceType: [{
          required: true,
          message: '请输入维修类别',
          trigger: 'blur'
        }],
        maintenanceContent: [{
          required: true,
          message: '请输入补充说明',
          trigger: 'blur'
        }],
        serviceFee: [{
          required: true,
          message: '请输入服务费',
          trigger: 'blur'
        }],
        partsFee: [{
          required: true,
          message: '请输入配件费',
          trigger: 'blur'
        }],
        maintenancePerson: [{
          required: true,
          message: '请输入维修人员',
          trigger: 'blur'
        }],
        totalFee: [{
          required: true,
          message: '请输入维修金额',
          trigger: 'blur'
        }],
      },
      beforePhotoAction: 'https://jsonplaceholder.typicode.com/posts/',
      beforePhotofileList: [],
      afterPhotoAction: 'https://jsonplaceholder.typicode.com/posts/',
      afterPhotofileList: [],


    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    /*this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg
    })*/
  },
  methods: {

    methodBefore(list){
      // console.log('接收url： ', list)
      this.formData.beforePhoto = list
      //console.log('赋值给变量beforePhoto：', this.formData.beforePhoto)
    },
    methodRe(list){
      // console.log('接收url： ', list)
      this.formData.afterPhoto = list
      //console.log('赋值给变量afterPhoto：', this.formData.afterPhoto)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true

      listRoadSign(this.queryParams).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },

    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        signCode: undefined,
        streetName: undefined,
        roadName: undefined,
        direction: undefined,
        location: undefined,
        remark: undefined
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "viewRecords":
          // alert('view')
         this.viewDetail(row)
          break
        case "addRecords":
          // alert('add')
          console.log('addFixRecords: ', row)
          this.fixDialog = true
          this.formData.signCode = row.signCode

          break
        default:
          break
      }
    },

    viewDetail(item) {
      console.log(item)
      this.$router.push({
        path: '/gift/maintenance',
        query: {
          row:item
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加地名指示牌信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const userId = row.id || this.ids
      getRoad(userId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改用户"
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value)
        })
      }).catch(() => {
      })
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId
      this.$router.push("/system/user-auth/role/" + userId)
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {

            roadSignUpdate(this.form).then(res => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })

          } else {
            addRoadSign(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roadId = row.id || this.ids
      this.$modal.confirm('是否确认删除用户id为"' + roadId + '"的数据项？').then(function () {
        return delRoadSign(roadId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },


    onOpen() {},
    onClose() {
      this.fixDialog = false
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.fixDialog = false
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // console.log('提交表单参数：', this.formData)
        addMaintenance(this.formData).then(res => {
          this.$message.success('新增维护记录成功！')
          this.fixDialog = false
        }).catch(err => {
          this.$message.error('新增维护记录失败！')
          console.log(err)
        }).finally(()=>{
          this.fixDialog = false
        })

        this.close()
      })
    },
    beforePhotoBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    afterPhotoBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },



  }
}
</script>
